package cn.com.kh.batch;

import cn.com.kh.FDDUtils;
import cn.com.kh.KHUtil;
import cn.com.kh.result.iAPIResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title: cn.com.dev-DevTao
 * @Description:ngsapitask-ph 系统API接口开发Demo，重点关注业务逻辑部分
 * @Author: lijun
 * @Date 2021-12-03 10:23
 */
public class BatchDeal_Utils {
    private static final Log log = LogFactory.getLog(BatchDeal_Utils.class);
    private static int i_Num = 0;

    /* 0-启动处理批次任务 */
    public static JSONObject runDealBatch(JdbcTemplate jt, String batchId, Map<String, Integer> stopFlagMap) {
        JSONObject resJson = iAPIResult.ERROR("启动处理批次任务 Init");

        try {
            // 根据批次号获取待推送一体化客户号
            List<Map<String, Object>> selectSignList = jt.queryForList("Select Rec_Guid, Field_1 As Cc_CustomerIds, Account_No As Cc_CustomerMobiles From Ph_Contract_Sign_List Where Step = 0 And Step_State = 0 And Batch_Id = ? Order By Created_Date", batchId);

            int total_Num = selectSignList.size();
            int loop_Num = 0;
            for (Map<String, Object> signMap : selectSignList) {
                if (stopFlagMap.get(batchId) != 1) {
                    throw new Exception("合同数据循环推送被暂停-中断调用⛔");
                }
                loop_Num++;
                log.debug("☘✅循环检查处理批次" + batchId + " 任务(" + loop_Num + "/" + total_Num + ")明细signMap:" + signMap);

                // 获取导入的客户信息
                String rec_Guid = FDDUtils.GetMapV(signMap, "Rec_Guid");
                String Cc_CustomerIds = FDDUtils.GetMapV(signMap, "Cc_CustomerIds");
                String Cc_CustomerMobiles = FDDUtils.GetMapV(signMap, "Cc_CustomerMobiles");
                BatchData_Utils.updateStep(jt, "1", rec_Guid);

                // 循环检查处理导入的客户编号(注册->认证)
                String[] customerIdsArr = Cc_CustomerIds.split(",");
                String[] customerMobilesArr = Cc_CustomerMobiles.split(",");
                log.debug("循环检查处理导入的客户编号:" + Arrays.toString(customerIdsArr));

                int i_WaitAuth_Num = 0;
                int i_SuccAuth_Num = 0;
                boolean is_FailFlag = false; // 是否出现客户信息校验过程出错,出错后整个任务不在执行
                boolean is_NextFlag = false;
                for (int i = 0; i < customerIdsArr.length; i++) {
                    String Cc_CustomerId = customerIdsArr[i];
                    String Cc_CustomerMobile = customerMobilesArr[i];
                    JSONObject res_RegJson = custRegister(jt, rec_Guid, Cc_CustomerId, Cc_CustomerMobile);
                    log.debug("-循环检查处理导入的客户编号(注册->认证) Cc_CustomerId:" + Cc_CustomerId + " Cc_CustomerMobile:" + Cc_CustomerMobile + " res_RegJson:" + res_RegJson);

                    String res_Code = KHUtil.GetSFJV(res_RegJson, "code");
                    String res_Msg = KHUtil.GetSFJV(res_RegJson, "msg");

                    // res_Code=0 等待认证 res_Code=1检查通过(已注册&已认证) res_Code=-1->异常
                    if (res_Code.equals("0")) {
                        i_WaitAuth_Num++;
                    } else if (res_Code.equals("-1")) {
                        is_FailFlag = true;
                        log.warn("批次batchId:" + batchId + " rec_Guid:" + rec_Guid + " Cc_CustomerId:" + Cc_CustomerId + " 循环检查处理导入的客户编号(注册->认证)-返回错误,任务结束");
                        BatchData_Utils.updateStep_APICode(jt, "-1", res_Code, "循环检查处理导入的客户编号(注册->认证)-返回错误(" + res_Msg + "),任务结束", rec_Guid);
                        break;
                    } else if (res_Code.equals("1")) {
                        i_SuccAuth_Num++;
                    }
                }

                // 如果客户信息注册推送认证过程出现失败则任务停止
                if (!is_FailFlag) {
                    // 记录主表批量处理进度
                    BatchData_Utils.updateStep_APICode(jt, "1", "1", "推送注册认证完成", rec_Guid);

                    // 判断是否全部注册且认证完成,如果全部完成,标记进行下一步动作
                    if (i_WaitAuth_Num == 0 && i_SuccAuth_Num > 0) {

                        is_NextFlag = true;
                        log.debug("判断是否全部注册且认证完成,如果全部完成,标记进行下一步动作：" + is_NextFlag);

                    }

                    // 判断是否直接(涉及客户已经全部认证完成)继续下一步->创建合同->推送签署
                    if (is_NextFlag) {

                        // 记录主表任务到
                        BatchData_Utils.updateStep(jt, "3", rec_Guid);

                        // 创建合同
                        JSONObject res_CreateCont = BatchDeal_Utils.createContract(jt, rec_Guid);
                        log.debug("生成合同完成-返回合同生成结果：" + res_CreateCont);

                        // 解析合同生成结果
                        String res_Code = KHUtil.GetSFJV(res_CreateCont, "code");
                        String res_Msg = KHUtil.GetSFJV(res_CreateCont, "msg");
                        if (res_Code.equals("1")) {
                            // 记录主表批量处理进度
                            BatchData_Utils.updateStep_APICode(jt, "3", res_Code, "认证全部完成-创建合同成功->推送签署ing", rec_Guid);

                            // 推送签署
                            BatchData_Utils.updateStep(jt, "4", rec_Guid);
                            JSONObject res_PushSign = BatchDeal_Utils.pushSign(jt, rec_Guid);
                            log.debug("推送签署返回对象：" + res_PushSign);

                        } else {
                            BatchData_Utils.updateStep_APICode(jt, "-3", res_Code, "创建合同错误:" + res_Msg, rec_Guid);

                        }

                    } else {
                        // 合同涉及客户并未全部注册完成
                        BatchData_Utils.updateStep(jt, "2", rec_Guid);

                    }
                } else {
                    log.warn("⛔当前任务客户信息检查注册&认证失败跳过继续执行 signMap:" + signMap);

                }

                // 休眠-防止法大大挂掉
                Thread.sleep(3000);
            }

            // 查询已认证但发送暂停后未生产合同的数据
            List<Map<String, Object>> selectAuthList = jt.queryForList("Select Rec_Guid, Field_1 As Customerid, Account_No From Ph_Contract_Sign_List Where Step = 2 And Step_State = 2 And Batch_Id = '" + batchId + "' Order By Created_Date");
            log.debug("☢查询已认证但发送暂停后未生产合同的数据：" + selectAuthList);

            for (int i = 0; i < selectAuthList.size(); i++) {
                Map<String, Object> authMap = selectAuthList.get(i);

                // 获取导入的客户信息
                String rec_Guid = FDDUtils.GetMapV(authMap, "Rec_Guid");
                BatchData_Utils.updateStep(jt, "3", rec_Guid);

                // 创建合同
                JSONObject res_CreateCont = BatchDeal_Utils.createContract(jt, rec_Guid);
                log.debug("生成合同完成-返回合同编号：" + res_CreateCont);

                // 解析合同生成结果
                String res_Code = KHUtil.GetSFJV(res_CreateCont, "code");
                String res_Msg = KHUtil.GetSFJV(res_CreateCont, "msg");
                if (res_Code.equals("1")) {
                    // 记录主表批量处理进度
                    BatchData_Utils.updateStep_APICode(jt, "3", res_Code, "认证全部完成-创建合同成功->推送签署ing", rec_Guid);

                    // 推送签署
                    BatchData_Utils.updateStep(jt, "4", rec_Guid);
                    JSONObject res_PushSign = BatchDeal_Utils.pushSign(jt, rec_Guid);
                    log.debug("推送签署返回对象：" + res_PushSign);

                } else {
                    BatchData_Utils.updateStep_APICode(jt, "-3", res_Code, "创建合同错误:" + res_Msg, rec_Guid);

                }

            }

            // 检查批次任务是否全部处理
            List<Map<String, Object>> selectNoDealList = jt.queryForList("Select Rec_Guid From Ph_Contract_Sign_List Where Batch_Id = '" + batchId + "' And Step = 1 And Step_State = 1");
            log.debug("☢检查批次任务是否全部处理：" + selectAuthList);
            if (selectNoDealList.size() == 0) {
                jt.update("Update Ph_Contract_Sign_Batch Set Send_Status = 2 Where Batch_Id = '" + batchId + "'");
            }

            // 返回调用处理结果
            resJson = iAPIResult.SUCCESS("批次推送签署合同完成", "循环检查处理批次" + batchId + " 任务数量:" + loop_Num + "/" + total_Num);
        } catch (Exception e) {
            resJson = iAPIResult.ERROR("批次推送签署合同异常(" + e.getMessage() + ")");
            log.error("⛔批次推送签署合同异常(" + e.getMessage() + ")", e);
        }
        log.debug("♻启动处理批次任务运行完成：" + resJson);
        return resJson;
    }

    /* 1-用户注册 */
    public static JSONObject custRegister(JdbcTemplate jt, String Rec_Guid, String CustomerID, String in_Mobile) {
        JSONObject result = new JSONObject();//返回报文
        log.debug("1-用户注册 Rec_Guid:" + Rec_Guid + " CustomerID:" + CustomerID + " in_Mobile:" + in_Mobile);
        try {
            // 获取一体化客户信息
            JSONObject resDBC_CustInfo = FCallAPI_Utils.getDBC_CustInfo(jt, Rec_Guid, CustomerID);
            log.debug("获取一体化客户信息ByCustomerID :" + resDBC_CustInfo);

            String res_Code = KHUtil.GetSFJV(resDBC_CustInfo, "code");
            String res_Msg = KHUtil.GetSFJV(resDBC_CustInfo, "msg");

            // 检查获取内部是否成功
            if (res_Code.equals("1")) {
                JSONObject res_Data = resDBC_CustInfo.getJSONObject("data");
                String res_status = KHUtil.GetSFJV(res_Data, "status");
                String res_message = KHUtil.GetSFJV(res_Data, "message");

                // 检查一体化是否成功
                if (res_status.equals("200")) {

                    JSONObject res_DbcData = res_Data.getJSONObject("data");
                    log.debug("Fix-一体化系统返回用户/企业信息Data数据:" + res_DbcData);

                    String Dbc_CustomerId = KHUtil.GetSFJV(res_DbcData, "customerid");
                    String Dbc_CustomerName = KHUtil.GetSFJV(res_DbcData, "customername");
                    String Dbc_customeroid = KHUtil.GetSFJV(res_DbcData, "customeroid");
                    String Dbc_customertypename = KHUtil.GetSFJV(res_DbcData, "customertypename");
                    String Dbc_idno = KHUtil.GetSFJV(res_DbcData, "idno");
                    String Dbc_Mobile = KHUtil.GetSFJV(res_DbcData, "mobile");
                    String Dbc_sex = KHUtil.GetSFJV(res_DbcData, "sex");
                    String Dbc_address = KHUtil.GetSFJV(res_DbcData, "address");
                    String Dbc_isCompany = KHUtil.GetSFJV(res_DbcData, "iscompany");

                    // 检查导入手机号和一体化手机号是否一致
                    if (KHUtil.isNull(in_Mobile) || Dbc_Mobile.equals(in_Mobile)) {

                        String checkSQL = "Select Customer_Guid, Customername, Fdd_Customerid From Customer Where Customerid = ? Or Customerid2 = ? Order By Modifieddate Desc Limit 1";
                        List<Map<String, Object>> checkList = jt.queryForList(checkSQL, Dbc_CustomerId, Dbc_CustomerId);
                        log.debug("Fix-查询系统Customer表是否存在CustomerID对应客户信息:" + checkList.size());

                        String Customer_Guid = KHUtil.getRandomString(36).toUpperCase();
                        if (checkList.size() > 0) {
                            Customer_Guid = checkList.get(0).get("Customer_Guid").toString();
                            i_Num = jt.update("Update Customer Set Customername = '" + Dbc_CustomerName + "', Customer_Id = '" + Dbc_idno + "', Gender = '" + Dbc_sex + "', Mobile = '" + Dbc_Mobile + "', Idtype = '" + Dbc_customertypename + "', Customerid2 = '" + Dbc_customeroid + "', Address = '" + Dbc_address + "', Customertype = '" + Dbc_isCompany + "' Where Customer_Guid = ?", Customer_Guid);
                            log.debug("Fix-海吉星Customer已存在客户基础信息,将最新一体化信息更新到Customer-更新DB数据:" + i_Num);
                        } else {
                            i_Num = jt.update("Insert Into Customer (Customer_Guid, Customername, Customerid, Customer_Id, Gender, Mobile, Idtype, Customerid2, Createdby, Createddate, Fdd_Customerid, Address, Customertype, Stringfield9) Values (?, '" + Dbc_CustomerName + "', '" + Dbc_CustomerId + "', '" + Dbc_idno + "', '" + Dbc_sex + "', '" + Dbc_Mobile + "', '" + Dbc_customertypename + "', '" + Dbc_customeroid + "', 'SELITE', Now(), '', '" + Dbc_address + "', '" + Dbc_isCompany + "', '" + Dbc_CustomerId + "')", Customer_Guid);
                            log.debug("Fix-海吉星Customer未存在客户基础信息-Add新增数据:" + i_Num);

                        }

                        // 法大大用户信息处理
                        if (Dbc_isCompany.equals("个人")) {
                            // 查询法大大接口获取用户状态
                            JSONObject res_PersonInfo = FCallAPI_Utils.getFDDPersonInfo(jt, Rec_Guid, Dbc_Mobile);

                            log.debug("获取[" + Dbc_Mobile + "][" + Rec_Guid + "]法大大客户基础信息 结果：" + res_PersonInfo);

                            String Fdd_CustomerId = "";
                            String verifiedStatus = "";
                            String verifiedStatusDesc = "";

                            if (KHUtil.GetSFJV(res_PersonInfo, "code").equals("1")) { // 查询到客户信息

                                // 获取法大大接口返回内容
                                JSONObject res_FddPersonInfo = res_PersonInfo.getJSONObject("data");
                                if (KHUtil.GetSFJV(res_FddPersonInfo, "code").equals("1")) {
                                    if (res_FddPersonInfo.getJSONArray("data").size() > 0) {
                                        Fdd_CustomerId = KHUtil.GetSFJV(res_FddPersonInfo.getJSONArray("data").getJSONObject(0), "customerId");
                                        verifiedStatus = KHUtil.GetSFJV(res_FddPersonInfo.getJSONArray("data").getJSONObject(0), "verifiedStatus");
                                        verifiedStatusDesc = KHUtil.GetSFJV(res_FddPersonInfo.getJSONArray("data").getJSONObject(0), "verifiedStatusDesc");

                                        // 将获取到的FDD客户编号和最新认证状态更新到Customer
                                        i_Num = jt.update("Update Customer Set Fdd_Customerid = ?, Fdd_Status = ?, Fdd_Reason = ?, Modifiedby = 'SELITE', Modifieddate = Now() Where Customer_Guid = " + "?", Fdd_CustomerId, verifiedStatus, verifiedStatusDesc, Customer_Guid);
                                        log.debug("Fix-将FDD用户对应的信息更新到Customer-更新DB数据:" + i_Num);

                                        // 识别FDD客户认证状态
                                        if (verifiedStatus.equals("1")) { // 未认证
                                            JSONObject res_PersonVerify = FCallAPI_Utils.doFDDPersonVerify(jt, Rec_Guid, Dbc_CustomerId, Fdd_CustomerId, Dbc_Mobile);
                                            log.debug("Fix-根据用户信息 识别FDD客户认证状态-未认证,已推送认证:" + res_PersonVerify);

                                            jt.update("Insert Into Sys_Oper_Log_Auth (Oper_Id, Rec_Guid, Customer_Id, Customer_Guid, Fdd_Customer_Id, Push_Type, Push_Time) Values (Uuid(), ?, ?, ?, ?, '认证', Now())", Rec_Guid, CustomerID, Customer_Guid, Fdd_CustomerId);

                                            result = iAPIResult.WARN("识别FDD客户认证状态-未认证,已推送认证-等待认证回调...");

                                        } else if (verifiedStatus.equals("2")) { // 已认证-通过
                                            log.debug("Fix-根据用户信息 识别FDD客户认证状态-已认证通过");

                                            JSONObject res_JsonData = new JSONObject();
                                            res_JsonData.put("Fdd_CustomerId", Fdd_CustomerId);
                                            res_JsonData.put("verifiedStatus", verifiedStatus);
                                            res_JsonData.put("verifiedStatusDesc", verifiedStatusDesc);
                                            result = iAPIResult.SUCCESS("识别FDD客户认证状态-已认证通过-可进行下一步操作", res_JsonData);


                                        } else {
                                            result = iAPIResult.ERROR("识别FDD客户认证状态错误(法大大错误)-" + verifiedStatus + "/" + verifiedStatusDesc, res_FddPersonInfo);

                                        }

                                    } else { // 未查询到客户信息

                                        // 未查询到客户信息 新注册客户
                                        JSONObject res_PersonRegi = FCallAPI_Utils.doFDDPersonRegi(jt, Rec_Guid, Dbc_Mobile);

                                        if (KHUtil.GetSFJV(res_PersonRegi, "code").equals("1")) {
                                            JSONObject res_FddPersonRegi = res_PersonRegi.getJSONObject("data");
                                            // 如果法大大返回 1成功或1001003已存在均是成功
                                            if (KHUtil.GetSFJV(res_FddPersonRegi, "code").equals("1") || KHUtil.GetSFJV(res_FddPersonRegi, "code").equals("1001003")) {
                                                Fdd_CustomerId = KHUtil.GetSFJV(res_FddPersonRegi, "data");

                                                // 将获取到的FDD客户编号更新到Customer
                                                i_Num = jt.update("Update Customer Set Fdd_Customerid = ?, Modifiedby = 'SELITE', Modifieddate = Now() Where Customer_Guid = ?", Fdd_CustomerId, Customer_Guid);
                                                log.debug("Fix-新注册客户后,FDD客户编号更新到Customer-更新DB数据:" + i_Num);

                                                // 新建客户后直接推送发起认证
                                                JSONObject res_PersonVerify = FCallAPI_Utils.doFDDPersonVerify(jt, Rec_Guid, Dbc_CustomerId, Fdd_CustomerId, Dbc_Mobile);
                                                log.debug("Fix-新注册客户后直接推送发起认证,推送认证:" + res_PersonVerify);

                                                jt.update("Insert Into Sys_Oper_Log_Auth (Oper_Id, Rec_Guid, Customer_Id, Customer_Guid, Fdd_Customer_Id, Push_Type, Push_Time) Values (Uuid(), ?, ?, ?, ?, '认证', Now())", Rec_Guid, CustomerID, Customer_Guid, Fdd_CustomerId);

                                                result = iAPIResult.WARN("新注册客户后直接推送发起认证,已推送认证-等待认证回调...");

                                            } else {
                                                result = iAPIResult.ERROR("调用法大大创建客户(法大大错误)-" + KHUtil.GetSFJV(res_FddPersonRegi, "msg"), res_FddPersonRegi);

                                            }


                                        } else {
                                            result = iAPIResult.ERROR("调用法大大创建客户(内部错误)-" + KHUtil.GetSFJV(res_PersonRegi, "msg"), res_PersonRegi);
                                        }

                                    }

                                } else {
                                    result = iAPIResult.ERROR("调用法大大查询客户(法大大错误)-" + KHUtil.GetSFJV(res_FddPersonInfo, "msg"), res_FddPersonInfo);

                                }
                            } else {
                                result = iAPIResult.ERROR("调用法大大查询客户(内部错误)-" + KHUtil.GetSFJV(res_PersonInfo, "msg"), res_PersonInfo);

                            }


                        } else if (Dbc_isCompany.equals("公司")) {

                            // 查询法大大接口获取企业状态
                            JSONObject res_CompanyInfo = FCallAPI_Utils.getFDDCompanyInfo(jt, Rec_Guid, Dbc_CustomerName);

                            log.debug("获取[" + Dbc_CustomerName + "][" + Rec_Guid + "]法大大企业基础信息 结果：" + res_CompanyInfo);

                            String Fdd_CustomerId = "";
                            String Fdd_CompanyId = "";
                            String verifiedStatus = "";
                            String verifiedStatusDesc = "";

                            if (KHUtil.GetSFJV(res_CompanyInfo, "code").equals("1")) { // 查询到企业信息

                                JSONObject res_FddCompanyInfo = res_CompanyInfo.getJSONObject("data");
                                // Code 1 法大大返回有信息 1001005其实是没有查到企业信息 这两种情况不属于错误
                                if (KHUtil.GetSFJV(res_FddCompanyInfo, "code").equals("1") || KHUtil.GetSFJV(res_FddCompanyInfo, "code").equals("1001005")) {
                                    // Code 1 法大大返回有信息 解析
                                    if (KHUtil.GetSFJV(res_FddCompanyInfo, "code").equals("1")) {
                                        Fdd_CompanyId = KHUtil.GetSFJV(res_FddCompanyInfo.getJSONArray("data").getJSONObject(0), "customerId");
                                        Fdd_CustomerId = KHUtil.GetSFJV(res_FddCompanyInfo.getJSONArray("data").getJSONObject(0).getJSONObject("companyAdminInfoVO"), "customerId");
                                        verifiedStatus = KHUtil.GetSFJV(res_FddCompanyInfo.getJSONArray("data").getJSONObject(0).getJSONObject("companyVerifiedStatusVO"), "verifiedStatus");
                                        verifiedStatusDesc = KHUtil.GetSFJV(res_FddCompanyInfo.getJSONArray("data").getJSONObject(0).getJSONObject("companyVerifiedStatusVO"), "verifiedStatusDesc");

                                        // 将获取到的FDD企业编号和最新认证状态更新到Customer
                                        i_Num = jt.update("Update Customer Set Fdd_Customerid = ?, Fdd_Status = ?, Fdd_Reason = ?, Modifiedby = 'SELITE', Modifieddate = Now(), Partner_Guid = ? " + "Where Customer_Guid = " + "?", Fdd_CompanyId, verifiedStatus, verifiedStatusDesc, Fdd_CustomerId, Customer_Guid);
                                        log.debug("Fix-将FDD企业对应的信息更新到Customer-更新DB数据:" + i_Num);

                                        // 识别FDD企业认证状态
                                        if (verifiedStatus.equals("0")) { // 未认证
                                            JSONObject res_CompanyVerify = FCallAPI_Utils.doFDDCompanyVerify(jt, Rec_Guid, Dbc_CustomerId, Fdd_CompanyId, Dbc_Mobile);

                                            log.debug("Fix-根据企业信息 识别FDD企业认证状态-未认证,已推送认证:" + res_CompanyVerify);

                                            jt.update("Insert Into Sys_Oper_Log_Auth (Oper_Id, Rec_Guid, Customer_Id, Customer_Guid, Fdd_Customer_Id, Push_Type, Push_Time) Values (Uuid(), ?, ?, ?, ?, '认证', Now())", Rec_Guid, CustomerID, Customer_Guid, Fdd_CompanyId);

                                            result = iAPIResult.WARN("识别FDD企业认证状态-未认证,已推送认证-等待认证回调...");

                                        } else if (verifiedStatus.equals("4")) { // 已认证-通过
                                            log.debug("Fix-根据企业信息 识别FDD企业认证状态-已认证通过");

                                            JSONObject res_JsonData = new JSONObject();
                                            res_JsonData.put("Fdd_CompanyId", Fdd_CompanyId);
                                            res_JsonData.put("Fdd_CustomerId", Fdd_CustomerId);
                                            res_JsonData.put("verifiedStatus", verifiedStatus);
                                            res_JsonData.put("verifiedStatusDesc", verifiedStatusDesc);
                                            result = iAPIResult.SUCCESS("识别FDD企业认证状态-已认证通过-可进行下一步操作", res_JsonData);

                                        } else {
                                            result = iAPIResult.ERROR("识别FDD企业认证状态错误(法大大错误)-" + verifiedStatus + "/" + verifiedStatusDesc, res_FddCompanyInfo);

                                        }

                                    } else { // 未查询到企业信息

                                        // 先注册个人
                                        JSONObject res_PersonRegi = FCallAPI_Utils.doFDDPersonRegi(jt, Rec_Guid, Dbc_Mobile);

                                        if (KHUtil.GetSFJV(res_PersonRegi, "code").equals("1")) {

                                            JSONObject res_FddPersonRegi = res_PersonRegi.getJSONObject("data");
                                            // 如果法大大返回 1成功或1001003已存在均是成功
                                            if (KHUtil.GetSFJV(res_FddPersonRegi, "code").equals("1") || KHUtil.GetSFJV(res_FddPersonRegi, "code").equals("1001003")) {
                                                Fdd_CustomerId = KHUtil.GetSFJV(res_FddPersonRegi, "data");

                                                // 未查询到企业信息 新注册企业
                                                JSONObject res_CompanyRegi = FCallAPI_Utils.doFDDCompanyRegi(jt, Rec_Guid, Fdd_CustomerId, Dbc_Mobile, Dbc_CustomerName);

                                                if (KHUtil.GetSFJV(res_CompanyRegi, "code").equals("1")) {

                                                    JSONObject res_FddCompanyRegi = res_CompanyRegi.getJSONObject("data");
                                                    // 如果法大大返回 1成功或1001003已存在均是成功
                                                    if (KHUtil.GetSFJV(res_FddCompanyRegi, "code").equals("1") || KHUtil.GetSFJV(res_FddCompanyRegi, "code").equals("1001003")) {
                                                        Fdd_CompanyId = KHUtil.GetSFJV(res_FddCompanyRegi, "data");

                                                        // 将获取到的FDD企业编号更新到Customer
                                                        i_Num = jt.update("Update Customer Set Fdd_Customerid = ?, Modifiedby = 'SELITE', Modifieddate = Now(), Partner_Guid = ? Where Customer_Guid " + "= ?", Fdd_CompanyId, Fdd_CustomerId, Customer_Guid);
                                                        log.debug("Fix-新注册企业后,FDD企业编号更新到Customer-更新DB数据:" + i_Num);

                                                        // 新建企业后直接推送发起认证
                                                        JSONObject res_CompanyVerify = FCallAPI_Utils.doFDDCompanyVerify(jt, Rec_Guid, Dbc_CustomerId, Fdd_CompanyId, Dbc_Mobile);
                                                        log.debug("Fix-新注册企业后直接推送发起认证,推送认证:" + res_CompanyVerify);

                                                        jt.update("Insert Into Sys_Oper_Log_Auth (Oper_Id, Rec_Guid, Customer_Id, Customer_Guid, Fdd_Customer_Id, Push_Type, Push_Time) Values (Uuid(), ?, ?, ?, ?, '认证', Now())", Rec_Guid, CustomerID, Customer_Guid, Fdd_CompanyId);

                                                        result = iAPIResult.WARN("新注册企业后直接推送发起认证,已推送认证-等待认证回调...");

                                                    } else {
                                                        result = iAPIResult.ERROR("调用法大大创建企业(法大大错误)-" + KHUtil.GetSFJV(res_FddCompanyRegi, "msg"), res_FddCompanyRegi);

                                                    }

                                                } else {
                                                    result = iAPIResult.ERROR("调用法大大创建企业(内部错误)-" + KHUtil.GetSFJV(res_CompanyRegi, "msg"), res_CompanyRegi);
                                                }


                                            } else {
                                                result = iAPIResult.ERROR("调用法大大企业创建用户(法大大错误)-" + KHUtil.GetSFJV(res_FddPersonRegi, "msg"), res_FddPersonRegi);

                                            }

                                        } else {
                                            result = iAPIResult.ERROR("调用法大大企业创建用户(内部错误)-" + KHUtil.GetSFJV(res_PersonRegi, "msg"), res_PersonRegi);
                                        }

                                    }

                                } else {
                                    result = iAPIResult.ERROR("调用法大大查询企业(法大大错误)-" + KHUtil.GetSFJV(res_CompanyInfo.getJSONObject("data"), "msg"), res_CompanyInfo);

                                }
                            } else {
                                result = iAPIResult.ERROR("调用法大大查询企业(内部错误)-" + KHUtil.GetSFJV(res_CompanyInfo, "msg"), res_CompanyInfo);

                            }

                        } else {
                            result = iAPIResult.ERROR("一体化系返回该用户/企业类型iscompany错误:" + Dbc_isCompany, res_DbcData);
                        }
                    } else {
                        result = iAPIResult.ERROR("导入企业手机号与一体化系统手机号不一致,一体化手机号:" + Dbc_Mobile, res_DbcData);
                    }
                } else {
                    result = iAPIResult.ERROR(res_message, res_Data);
                }
            } else {
                result = iAPIResult.ERROR(res_Msg, resDBC_CustInfo);
            }


        } catch (Exception e) {
            result = iAPIResult.ERROR("获取企业详细接口系统参数异常(" + e.getMessage() + ")");
            log.error("获取企业详细接口系统参数异常:" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 2-生成合同Main
     */
    public static JSONObject createContract(JdbcTemplate jt, String rec_Guid) {
        JSONObject result = new JSONObject();

        try {
            // 获取任务对应数据
            String getBaseSQL = "Select Field_1 As Cc_Customerids, Template_Id, Property_Number, Department_Id, Contract_Id, Step, Step_State From Ph_Contract_Sign_List Where Rec_Guid = '" + rec_Guid + "'";
            List<Map<String, Object>> getBaseList = jt.queryForList(getBaseSQL);
            log.debug("2-生成合同Main 获取任务对应数据：" + getBaseList.toString());

            if (getBaseList.size() > 0) {
                Map<String, Object> getBaseMap = getBaseList.get(0);
                String Cc_Customerids = KHUtil.GetMapV(getBaseMap, "Cc_Customerids");
                String Cc_Template_Id = KHUtil.GetMapV(getBaseMap, "Template_Id");
                String Cc_Property_Number = KHUtil.GetMapV(getBaseMap, "Property_Number");
                String Cc_Department_Id = KHUtil.GetMapV(getBaseMap, "Department_Id");
                String Cc_Contract_Id = KHUtil.GetMapV(getBaseMap, "Contract_Id");

                if (KHUtil.isNull(Cc_Contract_Id)) {
                    // 获取合同包ID
                    String Cc_FddGroupId = jt.queryForList("Select Fddgroup_Id From Fdd_Contract_File Where Contractfileid = '" + Cc_Template_Id + "'").get(0).get("Fddgroup_Id").toString();
                    log.debug("2-生成合同Main 获取合同包ID:" + Cc_FddGroupId);

                    // 获取拼接合同填充信息SQL
                    String getContractDetailSQL = getContentDataSQL(jt, Cc_Template_Id, rec_Guid);
                    log.debug("2-生成合同Main 获取拼接合同填充信息SQL:" + getContractDetailSQL);

                    List<Map<String, Object>> contractDataList = jt.queryForList(getContractDetailSQL);
                    Map<String, Object> contractDataMap = contractDataList.get(0);
                    log.debug("2-生成合同Main 获取拼接合同填充信息数据:" + contractDataMap.toString());

                    // 合同中特殊变量值初始化
                    String c_StartTime = "";
                    String c_EndTime = "";
                    String c_Years = "";

                    // 循环解析模版参数
                    JSONObject templateJson = new JSONObject();
                    for (String key : contractDataMap.keySet()) {
                        if (key.equals("starttime")) {
                            c_StartTime = KHUtil.GetMapV(contractDataMap, key);
                            log.debug("2-生成合同Main 合同中特殊变量值starttime:" + c_StartTime);
                        }
                        if (key.equals("endtime")) {
                            c_EndTime = KHUtil.GetMapV(contractDataMap, key);
                            log.debug("2-生成合同Main 合同中特殊变量值enddtime:" + c_EndTime);
                        }
                        if (key.equals("years")) {
                            c_Years = KHUtil.GetMapV(contractDataMap, key);
                            log.debug("2-生成合同Main 合同中特殊变量值years:" + c_Years);

                        }
                        // log.debug("循环解析模版参数key:" + key);
                        templateJson.put(key, KHUtil.GetMapV(contractDataMap, key));
                    }
                    log.debug("2-生成合同Main 循环解析模版参数完成:" + templateJson);

                    // 法大大调用Json初始化
                    JSONObject inJson = new JSONObject();
                    inJson.put("data", templateJson);

                    // 根据合同签署开始时间生成合同编号时间片段
                    Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(c_StartTime);
                    log.debug("2-生成合同Main 导入的签署开始时间转换后的日期：" + date);
                    String leaseTime = new SimpleDateFormat("yyyyMMdd").format(date);
                    log.debug("2-生成合同Main 根据合同签署开始时间生成合同编号时间片段：" + leaseTime);

                    // 根据不同的模板按不同的规则生成合同编号
                    String contractId = "";
                    switch (Cc_FddGroupId) {
                        case "CLELT3":
                            //生成合同编号
                            contractId = "SZHJX-ZL-" + Cc_Property_Number + "-" + leaseTime + KHUtil.getRandomString(4);
                            break;
                        case "H1DPF3":
                            //生成合同编号
                            contractId = "SZHJX-GD-" + Cc_Property_Number + "-" + leaseTime + KHUtil.getRandomString(4);
                            break;
                        case "VBFWBF":
                            //生成合同编号
                            contractId = "SZHJX-TZ-" + Cc_Property_Number + KHUtil.getRandomString(4);
                            break;
                    }

                    // 因法大大合同编号仅支持32位需要做长度保护
                    contractId = (contractId.length() > 32) ? (contractId.substring(0, 30) + KHUtil.getRandomString(2).toUpperCase()) : contractId.toUpperCase();
                    log.debug("2-生成合同Main ##根据不同的模板按不同的规则生成合同编号End(法大大合同编号仅支持32位需要做长度保护)：" + contractId);

                    // 获取组件列表
                    List<Object> assList = new ArrayList();
                    JSONObject assemblyPara = new JSONObject();
                    Iterator<String> keys = templateJson.keys();
                    while (keys.hasNext()) {
                        String commKey = keys.next();
                        // log.debug("获取组件列表 组件commKey: " + commKey);
                        assemblyPara.put("name", commKey);
                        assemblyPara.put("value", templateJson.getString(commKey));
                        // log.debug("获取组件列表 组件commKey-Para:" + assemblyPara);
                        assList.add(assemblyPara.toString());
                        assemblyPara.clear();
                    }
                    log.debug("2-生成合同Main 获取组件列表End assList:" + assList.toString());

                    // 获取合同发起方(归属方)&甲方签署人
                    String signatureSQL = "Select Group_Concat(Distinct F1.Signature Order By Find_In_Set(R1.Companycustomerid, F1.Signature)) As Signature,\n" + "       Group_Concat(Distinct R1.Yth_Gsname Order By Find_In_Set(R1.Companycustomerid, F1.Signature)) As Signature_Name,\n" + "       Group_Concat(Distinct R2.Customerid Order By Find_In_Set(R2.Customerid, F1.Fdd_Customerid)) As Sender_Guid,\n" + "       Group_Concat(Distinct Concat(R2.Yth_Gsname, '-', R2.Fdd_Type) Order By Find_In_Set(R2.Customerid, F1.Fdd_Customerid)) As Sender_Name\n" + "  From Fdd_Contract_File F1\n" + "  Left Join Fdd_Admin R1\n" + "    On Find_In_Set(R1.Companycustomerid, F1.Signature)\n" + "  Left Join Fdd_Admin R2\n" + "    On Find_In_Set(R2.Customerid, F1.Fdd_Customerid)\n" + " Where F1.Contractfileid = ?";
                    List<Map<String, Object>> signatureList = jt.queryForList(signatureSQL, Cc_Template_Id);
                    String signatureId = KHUtil.GetMapV(signatureList.get(0), "Signature");
                    String signatureName = KHUtil.GetMapV(signatureList.get(0), "Signature_Name");
                    String Sender_Guid = KHUtil.GetMapV(signatureList.get(0), "Sender_Guid");
                    String Sender_Name = KHUtil.GetMapV(signatureList.get(0), "Sender_Name");
                    log.debug("2-生成合同Main 获取合同发起方(归属方)&甲方签署人 signatureId:" + signatureId + " signatureName:" + signatureName + " Sender_Guid:" + Sender_Guid + " Sender_Name:" + Sender_Name);

                    // 编辑模板填充,直接生成合同
                    JSONObject fillContract = FCallAPI_Utils.doFDDContractCreate(jt, rec_Guid, assList, Cc_Template_Id, Cc_Property_Number, signatureId, contractId);
                    fillContract.put("contractId", contractId);
                    log.debug("2-生成合同Main 编辑模板填充 返回fillContract:" + fillContract);

                    String res_Code = KHUtil.GetSFJV(fillContract, "code");
                    String res_Msg = KHUtil.GetSFJV(fillContract, "msg");

                    // 检查获取内部是否成功
                    if (res_Code.equals("1")) {

                        // 获取乙方签署人并写入签署人表
                        String insertBSQL = "Insert Into Fdd_Agreement_List\n" + "  (Agreementduid,\n" + "   Workorderid,\n" + "   Modelid,\n" + "   Businessnumber,\n" + "   Contractid,\n" + "   Customerid,\n" + "   Ht_State,\n" + "   Ht_Type,\n" + "   Pushsigning,\n" + "   Ordernum,\n" + "   Createddate,\n" + "   Createdby,\n" + "   Customertype)\n" + "  Select Replace(Uuid(), '-', '') As Agreementduid,\n" + "         Pl.Rec_Guid As Workorderid,\n" + "         Pl.Template_Id,\n" + "         Pl.Property_Number,\n" + "         Pl.Contract_Id,\n" + "         C1.Fdd_Customerid,\n" + "         '未签署' As Ht_State,\n" + "         '客户' As Ht_Type,\n" + "         '未推送' As Pushsigning,\n" + "         Ifnull(Find_In_Set(C1.Customerid, Pl.Field_1), 0) As Ordernum,\n" + "         Now() As Createddate,\n" + "         'SELITE' As Createdby,\n" + "         If(C1.Customertype = '公司', 2, 1) As Customertype\n" + "    From Ph_Contract_Sign_List Pl\n" + "    Left Join Customer C1\n" + "      On Find_In_Set(C1.Customerid, Pl.Field_1)\n" + "   Where Pl.Rec_Guid = ?";
                        i_Num = jt.update(insertBSQL, rec_Guid);
                        log.debug("2-生成合同Main -获取乙方签署人并写入签署人表-更新DB数据:" + i_Num);

                        // 获取甲方签署人并写入签署人表
                        String insertASQL = "Insert Into Fdd_Agreement_List\n" + "  (Agreementduid,\n" + "   Workorderid,\n" + "   Modelid,\n" + "   Businessnumber,\n" + "   Contractid,\n" + "   Customerid,\n" + "   Ht_State,\n" + "   Ht_Type,\n" + "   Pushsigning,\n" + "   Ordernum,\n" + "   Createddate,\n" + "   Createdby,\n" + "   Customertype)\n" + "  Select Distinct Replace(Uuid(), '-', '') As Agreementduid,\n" + "                  Pl.Rec_Guid As Workorderid,\n" + "                  Pl.Template_Id,\n" + "                  Pl.Property_Number,\n" + "                  Pl.Contract_Id,\n" + "                  R2.Customerid,\n" + "                  '未签署' As Ht_State,\n" + "                  R2.Fdd_Type,\n" + "                  '未推送' As Pushsigning,\n" + "                  Ifnull(Find_In_Set(R2.Customerid, F1.Fdd_Customerid), 0) + R2.Ordernum As Ordernum,\n" + "                  Now() As Createddate,\n" + "                  'SELITE' As Createdby,\n" + "                  2 As Customertype\n" + "    From Ph_Contract_Sign_List Pl\n" + "    Left Join Fdd_Contract_File F1\n" + "      On Pl.Template_Id = F1.Contractfileid\n" + "    Left Join Fdd_Admin R2\n" + "      On Find_In_Set(R2.Customerid, F1.Fdd_Customerid)\n" + "   Where Pl.Rec_Guid = ?";
                        i_Num = jt.update(insertASQL, rec_Guid);
                        log.debug("2-生成合同Main -获取甲方签署人并写入签署人表-更新DB数据:" + i_Num);

                        // 查询获取乙方签署人Guid&名字
                        List<Map<String, Object>> signBList = jt.queryForList("Select Group_Concat(Distinct R1.Customerid Order By R1.Ordernum) As Customerid, Group_Concat(Distinct R2.Customername Order By R1.Ordernum) As Customername From Fdd_Agreement_List R1 Left Join Ph_Contract_Sign_List R11 On R1.Workorderid = R11.Rec_Guid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R11.Field_1) Where R1.Ht_Type = '客户' And R1.Workorderid = ?", rec_Guid);
                        String signerGuidList = KHUtil.GetMapV(signBList.get(0), "Customerid");
                        String signerNameList = KHUtil.GetMapV(signBList.get(0), "Customername");
                        log.debug("2-生成合同Main -查询获取乙方签署人Guid&名字 signBList:" + signBList);

                        // 将合同数据写入合同主表
                        i_Num = jt.update("Insert Into Fdd_Contract_List (Contractlist_Guid, Contractid, Contracttype, Contractfileid, Businessnumber, Departmentoid, Signer_Guid, Signer_Name, Sender_Guid, Sender_Name, Leaseapplicationtimestart, Leaseapplicationtimesend, Currentapplicationperiod, Createddate, Workorderid) " + "values (Uuid(), '" + contractId + "', '2', '" + Cc_Template_Id + "', '" + Cc_Property_Number + "', '" + Cc_Department_Id + "', '" + signerGuidList + "', '" + signerNameList + "', '" + signatureId + "', '" + signatureName + "', '" + c_StartTime + "', '" + c_EndTime + "', '" + c_Years + "', Now(), '" + rec_Guid + "')");
                        log.debug("2-生成合同Main -将合同数据写入合同主表-更新DB数据:" + i_Num);

                        // 创建合同结果
                        result = iAPIResult.SUCCESS("创建合同-合同生成成功", fillContract);

                    } else {
                        result = iAPIResult.ERROR("调用法大大查询企业(内部错误)-" + res_Msg, fillContract);
                    }
                } else {
                    result = iAPIResult.WARN("当前任务合同ID已经存在(合同疑似生成过):" + Cc_Contract_Id);
                }
            } else {
                result = iAPIResult.ERROR("未获取任务对应数据！");
            }
        } catch (Exception e) {
            result = iAPIResult.ERROR("2-生成合同Main 异常(" + e.getMessage() + ")");
            log.error("2-生成合同Main 异常:" + e.getMessage(), e);
        }

        log.debug("2-生成合同Main BatchDeal_Utils 创建生成合同通用createContract-生成合同结果:" + result);
        return result;
    }

    /**
     * 2-1-获取获取合同映射字段对应DataSQL(取模板字段使用是自然排序,此处也是自然排查,存在一定风险)
     */

    public static String getContentDataSQL(JdbcTemplate jt, String templateId, String rec_Guid) {

        // 初始化变量
        String sql_Part = "";
        StringBuilder fieldInfo = new StringBuilder();

        // 获取数据表字段集合
        List<Map<String, Object>> fieldList = jt.queryForList("Select Label_Id From Ph_Label_Sign Where Id > 6 Order By Id, Label_Id");
        JSONArray fieldArray = JSONArray.fromObject(fieldList);
        int field_Num = fieldArray.size();
        log.debug("获取数据表字段集合 数量:" + field_Num);

        // 获取模版字段映射集合
        List<Map<String, Object>> fddKeyList = jt.queryForList("Select Key_Guid, Work_Key, Fdd_Key, Keyname, Exp_Rule, Exp_Value, Seq_No From Fdd_Contract_Key Where Contractfileid = '" + templateId + "' Order By Seq_No, Keyname");
        JSONArray fddKeyJson = JSONArray.fromObject(fddKeyList);
        int fddKey_Num = fddKeyJson.size();
        log.debug("获取模版字段映射集合 数量:" + fddKey_Num);

        if (fddKey_Num <= field_Num) {
            // 循环获取拼接SQL
            for (int j = 0; j < fddKeyJson.size(); j++) {
                JSONObject fddKeyObject = fddKeyJson.getJSONObject(j);
                JSONObject fieldObject = fieldArray.getJSONObject(j);

                String Fdd_Key = KHUtil.GetSFJV(fddKeyObject, "Fdd_Key");
                String Keyname = KHUtil.GetSFJV(fddKeyObject, "Keyname");
                String Exp_Rule = KHUtil.GetSFJV(fddKeyObject, "Exp_Rule");
                String Exp_Value = KHUtil.GetSFJV(fddKeyObject, "Exp_Value");

                String DataField_Key = KHUtil.GetSFJV(fieldObject, "Label_Id");
                log.debug("获取导入数据和模版见字段映射关系-数据获取SQL Keyname:" + Keyname + " Fdd_Key:" + Fdd_Key + " Field_Key:" + DataField_Key + " Exp_Rule:" + Exp_Rule + " Exp_Value:" + Exp_Value);

                if (!KHUtil.isNull(Exp_Rule)) {
                    // 获取数据表字段和法大大字段映射 *如果字段中配置了正则校验
                    sql_Part = "If('" + Exp_Rule + "' = '', " + DataField_Key + ", If(" + DataField_Key + " Regexp '" + Exp_Rule + "' = 1, '" + Exp_Value + "', " + DataField_Key + ")) As '" + Fdd_Key + "',";
                } else {
                    // 获取数据表字段和法大大字段映射
                    sql_Part = DataField_Key + " As '" + Fdd_Key + "',";
                }
                fieldInfo.append(sql_Part);

            }
            fieldInfo = new StringBuilder(fieldInfo.substring(0, fieldInfo.length() - 1));
            fieldInfo = new StringBuilder("Select " + fieldInfo + " From Ph_Contract_Sign_List Where Rec_Guid = '" + rec_Guid + "'");
            log.debug("获取获取合同映射字段对应DataSQL:" + fieldInfo);
        } else {
            log.warn("模版映射表字段数量超出数据表字段数量, 数据配置异常, 请检查数量列和模版字段");
        }

        return fieldInfo.toString();
    }

    /**
     * 3-推送签署Main
     */
    public static JSONObject pushSign(JdbcTemplate jt, String rec_Guid) {
        JSONObject res_Json = new JSONObject();

        String selectNoSignSQL = "Select R0.Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, R1.Agreementduid, R1.Ordernum From Ph_Contract_Sign_List R0 Left Join Fdd_Agreement_List R1 On R0.Rec_Guid = R1.Workorderid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R0.Field_1) Left Join Fdd_Contract_File Fc On R0.Template_Id = Fc.Contractfileid Where R1.Pushsigning = '已推送' And R1.Ht_State = '未签署' And R0.Rec_Guid = ? Order By R1.Ordernum";
        List<Map<String, Object>> signNoSignList = jt.queryForList(selectNoSignSQL, rec_Guid);
        log.debug("3-推送签署Main 检查是否存在已推送&未签署任务:" + signNoSignList.toString());

        if (signNoSignList.size() > 0) {
            log.warn("3-推送签署Main 检查是否存在已推送&未签署任务:存在未签署任务");
            res_Json = iAPIResult.WARN("推送乙方签署结束:存在未签署乙方");

        } else {

            // 查询待签署乙方
            String selectBSQL = "Select R0.Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, R1.Agreementduid, R1.Ordernum From Ph_Contract_Sign_List R0 Left Join Fdd_Agreement_List R1 On R0.Rec_Guid = R1.Workorderid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R0.Field_1) Left Join Fdd_Contract_File Fc On R0.Template_Id = Fc.Contractfileid Where R1.Ht_Type = '客户' And R1.Pushsigning = '未推送' And R0.Rec_Guid = ? Order By R1.Ordernum";
            List<Map<String, Object>> signBList = jt.queryForList(selectBSQL, rec_Guid);
            log.debug("3-推送签署Main 查询待签署乙方:" + signBList.toString());

            if (signBList.size() > 0) {
                Map<String, Object> signBMap = signBList.get(0);
                BatchData_Utils.updateStep_State(jt, "4", "4", rec_Guid);

                res_Json = FCallAPI_Utils.pushPartyBSign(jt, rec_Guid, signBMap);

                // 解析合同生成结果
                String res_Code = KHUtil.GetSFJV(res_Json, "code");
                String res_Msg = KHUtil.GetSFJV(res_Json, "msg");
                if (res_Code.equals("1")) {
                    // 记录主表批量处理进度
                    BatchData_Utils.updateStep_APICode(jt, "6", res_Code, "等待乙方签署:" + signBMap, rec_Guid);

                    // 推送乙方签署结果
                    res_Json = iAPIResult.SUCCESS("推送乙方签署结束(剩余:" + (signBList.size() - 1) + ")", res_Json);
                    log.debug("推送乙方签署结果：" + res_Json);

                } else {
                    BatchData_Utils.updateStep_APICode(jt, "-4", res_Code, "推送乙方签署错误:" + res_Msg + " signBMap:" + signBMap, rec_Guid);

                    // 推送乙方签署结果
                    res_Json = iAPIResult.ERROR("推送乙方签署错误", res_Json);
                    log.debug("推送乙方签署结果：" + res_Json);

                }

            } else {
                String selectASQL = "Select R0.Rec_Guid, R1.Customertype, R1.Customerid, R1.Contractid, Fc.Fddgroup_Id, R1.Agreementduid, R1.Ordernum, R1.Ht_Type From Ph_Contract_Sign_List R0 Left Join Fdd_Agreement_List R1 On R0.Rec_Guid = R1.Workorderid Left Join Customer R2 On R1.Customerid = R2.Fdd_Customerid And Find_In_Set(R2.Customerid, R0.Field_1) Left Join Fdd_Contract_File Fc On R0.Template_Id = Fc.Contractfileid Where R1.Ht_Type In ('公司', '法人') And R1.Pushsigning = '未推送' And R0.Rec_Guid = ? Order By R1.Ordernum";
                List<Map<String, Object>> signAList = jt.queryForList(selectASQL, rec_Guid);
                log.debug("3-推送签署Main 查询待签署甲方:" + signAList.toString());

                if (signAList.size() > 0) {
                    Map<String, Object> signAMap = signAList.get(0);
                    BatchData_Utils.updateStep_State(jt, "5", "5", rec_Guid);

                    // 判断是否自动归档
                    String autoArchive = signAList.size() == 1 ? "1" : "2";

                    res_Json = FCallAPI_Utils.pushPartyASign(jt, rec_Guid, signAMap, autoArchive);

                    // 解析合同生成结果
                    String res_Code = KHUtil.GetSFJV(res_Json, "code");
                    String res_Msg = KHUtil.GetSFJV(res_Json, "msg");
                    if (res_Code.equals("1")) {
                        // 记录主表批量处理进度
                        BatchData_Utils.updateStep_APICode(jt, "7", res_Code, "等待甲方签署:" + signAMap, rec_Guid);

                        // 推送乙方签署结果
                        res_Json = iAPIResult.SUCCESS("推送甲方签署结束(剩余:" + (signAList.size() - 1) + ")", res_Json);
                        log.debug("推送甲方签署结果：" + res_Json);

                    } else {
                        BatchData_Utils.updateStep_APICode(jt, "-5", res_Code, "推送甲方签署错误:" + res_Msg + " signAMap:" + signAMap, rec_Guid);

                        // 推送乙方签署结果
                        res_Json = iAPIResult.ERROR("推送甲方签署错误", res_Json);
                        log.debug("推送甲方签署结果：" + res_Json);

                    }

                } else {
                    res_Json = iAPIResult.ERROR("推送签署结束", "未找到待签署任务");

                }

            }
        }

        return res_Json;
    }

    // 检查是否全部完成签署且回调完成
    public static void doTaskAllEndCheck(JdbcTemplate jt, String rec_Guid) {
        try {

            // 检查是否全部完成签署且回调完成
            String checkSQL = "Select Count(*) As Total_Num, Sum(If(R1.Pushsigning = '未推送', 1, 0)) As No_Push, Sum(If(R1.Pushsigning = '已推送', 1, 0)) As Push_Succ, Sum(If(R1.Pushsigning = '推送失败', 1, 0)) As Push_Fail, Sum(If(R1.Ht_State = '未签署', 1, 0)) As No_Sign, Sum(If(R1.Ht_State = '已签署', 1, 0)) As Sign_Succ, Sum(If(R1.Ht_State = '已拒签' Or R1.Ht_State = '拒签异常', 1, 0)) As Sign_Fail From Ph_Contract_Sign_List R0 Left Join Fdd_Agreement_List R1 On R0.Rec_Guid = R1.Workorderid Where R0.Rec_Guid = ?";
            List<Map<String, Object>> checkList = jt.queryForList(checkSQL, rec_Guid);
            log.debug("⏳✅检查是否全部完成签署且回调完成-结果:" + checkList);
            if (checkList.size() > 0) {
                Map<String, Object> checkMap = checkList.get(0);
                int Total_Num = Integer.parseInt(KHUtil.GetMapV(checkMap, "Total_Num"));
                int No_Push = Integer.parseInt(KHUtil.GetMapV(checkMap, "No_Push"));
                int Push_Succ = Integer.parseInt(KHUtil.GetMapV(checkMap, "Push_Succ"));
                int Push_Fail = Integer.parseInt(KHUtil.GetMapV(checkMap, "Push_Fail"));
                int No_Sign = Integer.parseInt(KHUtil.GetMapV(checkMap, "No_Sign"));
                int Sign_Succ = Integer.parseInt(KHUtil.GetMapV(checkMap, "Sign_Succ"));
                int Sign_Fail = Integer.parseInt(KHUtil.GetMapV(checkMap, "Sign_Fail"));

                if (No_Sign == 0) {
                    if (Total_Num == Sign_Succ) {
                        log.debug("检查是否全部完成签署且回调完成-签署完成(任务完成-End)");
                        BatchData_Utils.updateStep_All(jt, "10", "100", "-", "签署成功(End)", rec_Guid);
                    } else if (Total_Num == (Sign_Succ + Sign_Fail)) {
                        log.debug("检查是否全部完成签署且回调完成-签署失败(任务完成-End)");
                        BatchData_Utils.updateStep_All(jt, "10", "-100", "-", "签署失败(出现错误-End)", rec_Guid);
                    } else {
                        log.debug("检查是否全部完成签署且回调完成-未识别的签署状态数据");
                    }

                } else {
                    log.debug("检查是否全部完成签署且回调完成-存在等待回调的签署方");
                }

            }
        } catch (Exception e) {
            log.error("⛳检查是否全部完成签署且回调完成 处理异常(" + e.getMessage() + ")", e);
        }

    }

    // 检查当前客户是否还有其他待认证回调同步处理
    public static void doAuthOtherCheck(JdbcTemplate jt, String Main_Rec_Guid, String Cc_CustomerId, String callPram) {

        try {

            // 检查当前客户是否还有其他待认证回调同步处理
            String checkSQL = "Select Oper_Id, Rec_Guid, Customer_Id, Customer_Guid, Fdd_Customer_Id From Sys_Oper_Log_Auth Where Push_Type = '认证' And (Status = '' Or Status Is Null) And Customer_Id = ?";
            List<Map<String, Object>> checkList = jt.queryForList(checkSQL, Cc_CustomerId);
            log.debug("⏳✅检查当前客户是否还有其他待认证回调同步处理-结果:" + checkList);
            if (checkList.size() > 0) {

                // 接收客户端调用参数
                JSONObject bizContentJson = FDDUtils.callbackParse(callPram).getJSONObject("bizContent");

                String status = FDDUtils.GetSFJV(bizContentJson, "status"); // 获取状态
                String statusDesc = FDDUtils.GetSFJV(bizContentJson, "statusDesc"); // 获取状态描述
                String auditFailReason = FDDUtils.GetSFJV(bizContentJson, "auditFailReason"); // 获取失败原因

                for (int i = 0; i < checkList.size(); i++) {
                    Map<String, Object> checkMap = checkList.get(0);
                    String Oper_Id = KHUtil.GetMapV(checkMap, "Oper_Id");
                    String rec_Guid = KHUtil.GetMapV(checkMap, "Rec_Guid");

                    // 将回调结果更新到认证Log回调表
                    i_Num = jt.update("Update Sys_Oper_Log_Auth Set Status = ?, Statusdesc = ?, Remark = ?, Callback_Time = Now() Where Oper_Id = ?", status, statusDesc, Main_Rec_Guid + (KHUtil.isNull(auditFailReason) ? "(" + auditFailReason + "0" : ""), Oper_Id);
                    log.debug("检查当前客户是否还有其他待认证回调同步处理-更新DB数据:" + i_Num);

                    // 如果无失败原因说明认证通过
                    if (KHUtil.isNull(auditFailReason)) {
                        // 查询是否还有未认证通过的客户
                        List<Map<String, Object>> selectExits = jt.queryForList("Select R1.Oper_Id From Sys_Oper_Log_Auth R1 Left Join Customer R2 On R1.Customer_Guid = R2.Customer_Guid Where R1.Rec_Guid = ? And (R1.Status != If(Ifnull(R2.Customertype, '个人') = '公司', '4', '2') Or R1.Status Is Null Or R1.Status = '')", rec_Guid);

                        if (selectExits.size() == 0) {

                            // 记录主表批量处理进度
                            BatchData_Utils.updateStep(jt, "3", rec_Guid);

                            // 创建合同
                            JSONObject res_CreateCont = BatchDeal_Utils.createContract(jt, rec_Guid);
                            log.debug("生成合同完成-返回合同创建结果：" + res_CreateCont);

                            if (KHUtil.GetSFJV(res_CreateCont, "code").equals("1")) {
                                // 推送签署
                                BatchData_Utils.updateStep_APICode(jt, "3", KHUtil.GetSFJV(res_CreateCont, "code"), "认证全部完成-创建合同成功->推送签署ing", rec_Guid);
                                JSONObject res_PushSign = BatchDeal_Utils.pushSign(jt, rec_Guid);
                                log.debug("推送签署 返回结果：" + res_PushSign);
                            } else {
                                // 记录主表创建合同进度
                                BatchData_Utils.updateStep_APICode(jt, "-3", KHUtil.GetSFJV(res_CreateCont, "code"), "创建合同错误:" + KHUtil.GetSFJV(res_CreateCont, "msg"), rec_Guid);
                                log.debug("生成合同完成 返回失败：" + res_CreateCont);

                            }
                        }

                    } else {
                        // 记录主表批量处理进度-失败
                        BatchData_Utils.updateStep_APICode(jt, "-2", "-1", statusDesc + "(" + auditFailReason + "-任务结束)", rec_Guid);
                        log.debug("推送签署返回对象 记录主表批量处理进度-失败：" + statusDesc + "(" + auditFailReason + "-任务结束)");
                    }


                }
            }

        } catch (Exception e) {
            log.error("⛳检查当前客户是否还有其他待认证回调同步处理 异常(" + e.getMessage() + ")", e);
        }

    }
}